package com.yoooya.base.third.utils.http;

import com.yoooya.base.third.common.error.WxError;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;

/**
 * 简单的GET请求执行器，请求的参数是String, 返回的结果也是String
 * 
 * 
 * @创建人 Sun Yijing
 * @创建时间 2018-07-08
 */
public class SimpleGetRequestExecutor implements
		RequestExecutor<String, String> {

	@Override
	public String execute(CloseableHttpClient httpclient, String uri,
                          String queryParam) throws ClientProtocolException, IOException {
		if (queryParam != null) {
			if (uri.indexOf('?') == -1) {
				uri += '?';
			}
			uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
		}
		HttpGet httpGet = new HttpGet(uri);
		try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
			String responseContent = Utf8ResponseHandler.INSTANCE
					.handleResponse(response);
			WxError error = WxError.fromJson(responseContent);
			if (error.getErrorCode() != 0) {
				return "";
			}
			return responseContent;
		}
	}
}
